//
//  GlobalMethod.swift
//  全局方法
//
//  Created by mini on 2025/4/28.
//

import Foundation

class GlobalMethod: NSObject {
   
    // MARK: - delegate执行selector
    class func performSelector(selectorName: String, delegate: AnyObject) -> Any? {
        return self.performSelector(selectorName: selectorName, delegate: delegate, object: nil, isHasReturn: false)
    }

    class func performSelector(selectorName: String, delegate: AnyObject, object: Any?, isHasReturn: Bool) -> Any? {
        let selector = Selector(selectorName)
        if let delegate = delegate as AnyObject?, delegate.responds(to: selector) {
            if isHasReturn {
                let result = delegate.perform(selector, with: object)
                return result
            } else {
                _ = delegate.perform(selector, with: object)
                return nil
            }
        }
        return nil
    }

    class func performSelector(selectorName: String, delegate: AnyObject, object: Any?, object2: Any?, isHasReturn: Bool) -> Any? {
        let selector = Selector(selectorName)
        if let delegate = delegate as AnyObject?, delegate.responds(to: selector) {
            if isHasReturn {
                let result = delegate.perform(selector, with: object, with: object2)
                return result
            } else {
                _ = (delegate.perform(selector, with: object, with: object2))
                return nil
            }
        }
        return nil
    }
    
    // MARK: - 创建rootNav
    static func createRootNav() {
        if (GlobalMethod.readBoolFromUserDefaults(forKey: LOCAL_FIRST_INSTALL, isPrefixed: false) == false) {
            // 显示引导页
            let navMain = BaseNavController.init(rootViewController: GuideVC())
            navMain.isNavigationBarHidden = true
            GB_Nav = navMain;
        }
        else {
            // 显示首页
            let navMain = BaseNavController.init(rootViewController: BaseTabbarController.init())
            navMain.isNavigationBarHidden = true
            GB_Nav = navMain;
        }
        var window: UIWindow?
        if let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene {
          window = windowScene.windows.first
        }
        if window == nil {
          window = UIWindow(frame: UIScreen.main.bounds)
        }
        window?.rootViewController = GB_Nav
        window?.backgroundColor = UIColor.clear
        window?.makeKeyAndVisible()
        
        if let delegate = UIApplication.shared.delegate as? AppDelegate {
          delegate.window = window
        }
    }
    
    // MARK: - 重新/退出登陆
    static func relogin() {
        GlobalMethod.clearLocalUserInfo()
        GlobalMethod.createRootNav()
    }
    
    // MARK: - 注销
    // 清除全局数据
    static func clearLocalUserInfo() {
        let gbData: GlobalData = GlobalData.sharedInstance
        gbData.GB_UserModel = nil
        gbData.GB_SessionID = nil
        clearUserDefault()
    }
}
